<template>
  <el-drawer
    title="添加 / 编辑"
    size="60%"
    :wrapperClosable="false"
    :visible.sync="showModify"
  >
    <template slot="title">
      <span class="title">添加 / 编辑</span>
      <div class="btn-wrap">
        <el-button size="small" @click="close">关闭</el-button>
        <el-button type="primary" size="small" @click="save">提交</el-button>
      </div>
    </template>
    <div class="modify common-container">
      <div class="common-bot">
        <div class="modify-bot">
          <el-form ref="form" :model="form" label-width="100px">
            <el-form-item required label="客户端类型">
              <el-select v-model="form.clientType" placeholder="请选择">
                <el-option
                  v-for="item in clientTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item required label="权限名称">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item required label="权限简述">
              <el-input v-model="form.detail"></el-input>
            </el-form-item>
            <el-form-item label="排序值">
              <el-input v-model="form.queue"></el-input>
            </el-form-item>
            <el-form-item label="菜单权限明细">
              <div class="auth-wrap">
                <ul class="out">
                  <li
                    v-for="item in menuData"
                    :data-item-id="item.id"
                    :key="item.id">
                    <div class="left-cont">
                      <el-checkbox
                        v-model="item.checked"
                        @change="check('parent', item)"
                      >{{ item.name }}
                      </el-checkbox>
                    </div>
                    <div class="center-cont">
                      <div
                        class="center-item"
                        v-for="firstChild in item.children"
                        :key="firstChild.id">
                        <div class="center-left">
                          <el-checkbox
                            v-model="firstChild.checked"
                            @change="check('firstChild', firstChild, item)">
                            {{ firstChild.name }}
                          </el-checkbox>
                        </div>
                        <div class="center-right">
                          <div
                            class="right-item"
                            v-for="secondChild in firstChild.children"
                            :key="secondChild.id">
                            <el-checkbox
                              v-model="secondChild.checked"
                              @change="
                                check('secondChild', secondChild, firstChild)
                              ">{{ secondChild.name }}
                            </el-checkbox>
                          </div>
                        </div>
                      </div>
                    </div>
                  </li>
                </ul>
              </div>
            </el-form-item>
            <el-form-item label="接口权限明细">
              <div class="auth-wrap">
                <ul class="out">
                  <li
                    v-for="item in interfaceData"
                    :data-item-id="item.id"
                    :key="item.id">
                    <div class="left-cont">
                      <el-checkbox
                        v-model="item.checked"
                        @change="check('parent', item)"
                      >{{ item.name }}
                      </el-checkbox>
                    </div>
                    <div class="center-cont">
                      <div
                        class="center-item"
                        v-for="firstChild in item.children"
                        :key="firstChild.id">
                        <div class="center-left">
                          <el-checkbox
                            v-model="firstChild.checked"
                            @change="check('secondChild', firstChild, item)">
                            {{ firstChild.name }} ({{ firstChild.path }})
                          </el-checkbox>
                        </div>
                      </div>
                    </div>
                  </li>
                </ul>
              </div>
            </el-form-item>

            <el-form-item label="是否启用">
              <el-switch v-model="form.enable"></el-switch>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import Api from "@/api/index";

export default {
  props: {
    showModify: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "add",
    },
    id: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      dialogVisible: false,
      gender: {
        female: "女",
        male: "男",
      },
      form: {
        formId: 0,
        parentId: 0,
        clientType: 'administrators',
        name: "",
        detail: "",
        enable: true,
        queue: 0,
        roles: [],
        interfaces: [],
        userIds: [],
      },
      menuData: [],
      menuDataForUser: [],
      interfaceData: [],
      interfaceDataForUser: [],
      nowSelRoleUserArr: [],
      multipleSelection: [],
      clientTypeOptions: [
        {
          label: "系统管理员",
          value: "administrators",
        },
        {
          label: "用户",
          value: "users",
        },
        {
          label: "游客",
          value: "tourists",
        },
      ],
    };
  },
  watch: {
    async showModify(val) {
      if (val) {
        let data = await this.getAllAuth();
        this.menuData = this.formatAuth(data);
        let interfaces = await this.getAllInterfaces();
        this.interfaceData = this.formatAuth(interfaces);
        if (this.type == "edit") {
          this.getInfo();
        }
      }
    },
  },
  methods: {
    close() {
      this.$emit("close");
      this.resetForm();
    },
    resetForm() {
      this.form = {
        formId: 0,
        parentId: 0,
        name: "",
        detail: "",
        enable: true,
        queue: 0,
        roles: [],
        userIds: [],
      };
      this.nowSelRoleUserArr = [];
      this.multipleSelection = [];
    },
    //
    sureSelUser() {
      this.nowSelRoleUserArr = this.multipleSelection;
      this.dialogVisible = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getRowKeys(row) {
      return row.id;
    },
    remove(item) {
      this.$confirm("确认此操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let nowSelRoleUserArr = this.nowSelRoleUserArr;
        let flagIndex;
        nowSelRoleUserArr.forEach((oitem, index) => {
          if (oitem.id == item.id) {
            flagIndex = index;
          }
        });
        nowSelRoleUserArr.splice(flagIndex, 1);
        this.nowSelRoleUserArr = nowSelRoleUserArr;
      });
    },
    addToNowRoleGroup(item) {
      this.$refs.multipleTable.toggleRowSelection(item, true);
      let nowSelRoleUserArr = this.nowSelRoleUserArr;
      let flag = true;
      for (let i = 0; i < nowSelRoleUserArr.length; i++) {
        if (nowSelRoleUserArr[i].id == item.id) {
          flag = false;
        }
      }
      if (flag) {
        nowSelRoleUserArr.push(item);
        this.$refs.multipleTable.toggleRowSelection(item, true);
      }
      this.nowSelRoleUserArr = nowSelRoleUserArr;
    },
    getUser(roleGroupId = 0) {
      return new Promise((resolve, reject) => {
        Api.manager
          .list({
            limit: 100,
            page: 0,
            roleGroupId,
          })
          .then((res) => {
            resolve(res.data);
          });
      });
    },
    async addUser() {
      this.dialogVisible = true;
      let data = await this.getUser();
      this.menuDataForUser = data;
      let arr = [];
      data.forEach((item) => {
        for (let i = 0; i < this.nowSelRoleUserArr.length; i++) {
          if (item.id == this.nowSelRoleUserArr[i].id) {
            arr.push(item);
          }
        }
      });
      setTimeout(() => {
        arr.forEach((item) => {
          this.$refs.multipleTable.toggleRowSelection(item, true);
        });
      }, 100);
    },
    check(type, item, p = null) {
      let flag = false;
      switch (type) {
        case "parent":
          this.changeChecked(item);
          break;
        case "firstChild":
          // p.checked = item.checked;
          this.changeChecked(item);
          break;
        case "secondChild":
          for (let i = 0; i < p.children.length; i++) {
            if (p.children[i].checked) {
              flag = true;
            }
          }
          p.checked = flag;
          this.$nextTick(() => {
            this.rollBackChecked();
          });
          if (!flag) {
            this.changeChecked(item);
          }
          break;
        default:
          break;
      }
    },
    checkInfo() {
      if (String(this.form.name).trim() == "") {
        this.$message({
          type: "error",
          message: "请填写名称",
        });
        return false;
      }
      if (String(this.form.detail).trim() == "") {
        this.$message({
          type: "error",
          message: "请填写权限组简述",
        });
        return false;
      }
      if (this.form.roles.length == 0) {
        this.$message({
          type: "error",
          message: "请选择权限",
        });
        return false;
      }
      return true;
    },
    save() {
      let roles = [];
      let data = this.menuData;
      const format = (data) => {
        for (let i = 0; i < data.length; i++) {
          if (data[i].checked) {
            roles.push(data[i].id);
          }
          if (data[i].children) {
            format(data[i].children);
          }
        }
      };
      format(data);

      let interfaces = [];
      data = this.interfaceData;
      const format2 = (data) => {
        for (let i = 0; i < data.length; i++) {
          if (data[i].checked) {
            interfaces.push(data[i].id);
          }
          if (data[i].children) {
            format2(data[i].children);
          }
        }
      };
      format2(data);
      let userIds = [];
      for (let i = 0; i < this.nowSelRoleUserArr.length; i++) {
        userIds.push(this.nowSelRoleUserArr[i].id);
      }
      this.$set(this.form, "roles", roles);
      this.$set(this.form, "interfaces", interfaces);
      this.$set(this.form, "userIds", userIds);
      if (!this.checkInfo()) {
        return;
      }
      Api.roleGroup.modify(this.form).then((res) => {
        if (res.code == 200) {
          this.$message.success("操作成功");
          this.$emit("close");
        }
      });
    },
    // 初始换权限数组各参数
    formatAuth(data, pid = 0) {
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].checked = false;
          data[i].pid = pid;
          if (data[i].children) {
            this.formatAuth(data[i].children, data[i].id);
          }
        }
      }
      return data;
    },
    getAllAuth() {
      return new Promise((resolve, reject) => {
        Api.roleGroup.allRoles().then((res) => {
          resolve(res.data);
        });
      });
    },
    getAllInterfaces() {
      return new Promise((resolve, reject) => {
        Api.roleGroup.allInterfaces().then((res) => {
          resolve(res.data);
        });
      });
    },
    changeChecked(item) {
      // 树形级联操作
      let isChecked = item.checked;
      const format = (item) => {
        if (item.children) {
          let trueArr = [];
          for (let i = 0; i < item.children.length; i++) {
            if (item.children[i].checked) {
            }
            item.children[i].checked = isChecked;
            if (item.children[i].children) {
              for (let j = 0; j < item.children[i].children.length; j++) {
                format(item.children[i].children[j]);
              }
            }
          }
        } else {
          item.checked = isChecked;
        }
      };
      format(item);
      this.$nextTick(() => {
        this.rollBackChecked();
      });
      // this.rollChecked();
    },
    rollBackChecked() {
      let that = this;
      $(".auth-wrap li").each(function () {
        let itemId = $(this).data("item-id");
        if ($(this).find(".center-cont .el-checkbox.is-checked").length) {
          that.menuData.forEach((item) => {
            if (item.id == itemId) {
              item.checked = true;
              item.isChecked = true;
            }
          });
        } else {
          that.menuData.forEach((item) => {
            if (item.id == itemId) {
              item.checked = false;
              item.isChecked = false;
            }
          });
        }
      });
    },
    rollChecked() {
      let data = this.menuData;
      const format = (item, p = null) => {
        for (let i = 0; i < item.length; i++) {
          let flag = false;
          let trueArr = [];
          if (item[i].children) {
            for (let j = 0; j < item[i].children.length; j++) {
              if (item[i].children[j].checked) {
                trueArr.push(item[i].children[j]);
              }
              if (item[i].children[j].children) {
                format(item[i].children[j].children, item[i].children[j]);
              }
            }
            item[i].checked = trueArr.length > 0 ? true : false;
            trueArr = [];
          } else {
            if (item[i].checked) {
              trueArr.push(item[i]);
            }
            p.checked = trueArr.length > 0 ? true : false;
            trueArr = [];
          }
        }
      };
      format(data);
    },
    async getInfo() {
      let userData = await this.getUser(this.id);
      this.nowSelRoleUserArr = userData;
      Api.roleGroup.detail({
        targetId: this.id,
      }).then((res) => {
        let data = JSON.parse(JSON.stringify(this.menuData));
        let roles = res.data.roles;
        const format = (data) => {
          for (let i = 0; i < data.length; i++) {
            if (roles.indexOf(data[i].id) != -1) {
              data[i].checked = true;
            }
            if (data[i].children) {
              format(data[i].children);
            }
          }
        };
        format(data);
        this.menuData = data;

        let tempData = JSON.parse(JSON.stringify(this.interfaceData));
        let interfaces = res.data.interfaces;
        console.log(interfaces);
        const format2 = (data) => {
          for (let i = 0; i < data.length; i++) {
            if (interfaces.indexOf(data[i].id) != -1) {
              data[i].checked = true;
            }
            if (data[i].children) {
              format2(data[i].children);
            }
          }
        };
        format2(tempData);
        this.interfaceData = tempData;
        console.log(tempData);

        let userIds = [];
        for (let i = 0; i < userData.length; i++) {
          userIds.push(userData[i].id);
        }
        this.form = {
          formId: res.data.id,
          parentId: res.data.parentId,
          clientType: res.data.clientType,
          name: res.data.name,
          detail: res.data.detail,
          enable: res.data.enable,
          queue: res.data.queue,
          roles: res.data.roles,
          interfaces: res.data.interfaces,
          userIds,
        };
      });
    },
  },
};
</script>
<style scoped lang="scss">
.modify {
  .modify-bot {
    width: 100%;
    padding: 30px 10px;
    border-right: 1px solid #ddd;

    .auth-wrap {
      font-size: 0;
      margin-left: -40px;

      ul.out {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        font-size: 14px;

        li {
          display: flex;
          justify-content: center;
          align-items: top;
          width: 100%;
          border: 1px solid #ddd;
          border-bottom: none;

          .el-checkbox {
            margin-right: 10px;
          }

          &:last-child {
            border-bottom: 1px solid #ddd;
          }

          .left-cont {
            flex: 1.5;
            text-align: left;
            padding-left: 10px;
          }

          .center-cont {
            flex: 4;

            .center-item {
              border: 1px solid #ddd;
              border-bottom: none;
              text-align: left;
              display: flex;
              border-right: none;

              &:first-child {
                border-top: none;
              }

              .center-left {
                flex: 1.5;
                border-right: 1px solid #ddd;
                padding-left: 10px;
              }

              .center-right {
                flex: 3;
                display: flex;
                flex-wrap: wrap;
                padding-left: 10px;
              }
            }
          }
        }
      }
    }
  }

  .bot-right {
    .top {
      font-size: 12px;
      color: red;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
    }

    .seled-user-list {
      width: 90%;
    }
  }
}
</style>
